package com.suqiu.qqrobot.config;

import com.suqiu.qqrobot.common.exception.BusinessException;
import com.suqiu.qqrobot.common.result.Result;
import com.suqiu.qqrobot.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author suqiu
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.suqiu.qqrobot.controller"})
public class ControllerAdvice {

    /**
     * 参数校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<?> methodArgumentNotValidExceptionAdvice(MethodArgumentNotValidException e) {
        log.error("Exception.msg={}", e.getMessage(), e);
        List<String> strings = e.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        return Result.fail(ResultCodeEnum.PARAM_VALID_ERROR, strings.toString());
    }

    /**
     * 参数绑定异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public Result<?> bindExceptionAdvice(BindException e) {
        List<String> strings = e.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
        log.error("Exception.msg={}", e.getMessage(), e);
        return Result.fail(ResultCodeEnum.PARAM_BIND_ERROR, strings.toString());
    }

    /**
     * 业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public Result<?> businessExceptionAdvice(BusinessException e) {
        log.error("Exception.msg={}", e.getMessage(), e);
        return Result.fail(ResultCodeEnum.INTERNAL_SERVER_ERROR, e.getMessage());
    }


    /**
     * 所有异常统一处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result<?> AllExceptionAdvice(Exception e) {
        log.error("Exception.msg={}", e.getMessage(), e);
        return Result.fail(ResultCodeEnum.INTERNAL_SERVER_ERROR, e.getMessage());
    }

}
